package org.example.mall.admin.configuration.email;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 邮箱服务端点
 *
 * @author hzq
 * @since 2021-06-28
 */
@Slf4j
@Component
@AllArgsConstructor
public class EmailEndpoint {

    private final JavaMailSender javaMailSender;
    private final MailProperties mailProperties;
    private final TemplateEngine templateEngine;

    /**
     * 发送简单邮箱
     *
     * @param to      接收方
     * @param cc      抄送
     * @param subject 标题
     * @param content 内容
     */
    public Boolean sendSimpleMail(String to, String cc, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        try {
            simpleMailMessage.setFrom(mailProperties.getUsername());
            simpleMailMessage.setTo(to);
            simpleMailMessage.setCc(cc);
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(content);
            javaMailSender.send(simpleMailMessage);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("发送邮件失败、邮件消息:{}", simpleMailMessage);
            return Boolean.FALSE;
        }
    }

    /**
     * 发送邮箱
     *
     * @param email  邮箱
     * @param scenes 场景
     * @param code   验证码
     * @return 发送 成功/失败
     */
    public Boolean sendEmailCode(String email, String scenes, String code) {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            helper.setTo(email);
            helper.setFrom(mailProperties.getUsername());
            helper.setSubject("验证码");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("code", code);
            String mail = templateEngine.process("email-code/" + scenes, context);
            helper.setText(mail, true);
            javaMailSender.send(msg);
            log.debug("发送邮箱登录验证码成功");
            return Boolean.TRUE;
        } catch (MessagingException e) {
            log.error("邮件发送失败：{}", e.getMessage());
            return Boolean.FALSE;
        }
    }
}
